import { useEffect } from 'react'
import constConfig from '../constant'
import { reportVodData } from '@/api/vod'
import { reportVodHistory, reportLiveHistory } from '@/api/history-collect'
import { cacheHistory } from '@/utils/utils'
import { ReactVideo, useSetErrorCode } from '../react-video'
import omit from 'lodash-es/omit'
import { useRouter } from 'next/router'
//点播热门上报,播放时长大于10s再上报
const reportHotVod = (progress, info) => {
  if (progress < 10) {
    return
  }
  reportVodData(info?.cid)
}

// 观看历史上报
const reportHistory = from => {
  if (from !== 'VOD' && from !== 'LIVE') {
    return
  }
  const latestParams = (from === 'VOD' ? window.varReport : window.varLiveReport) || {} //区分点播和直播
  const token = localStorage.getItem('token')
  if (from === 'VOD') {
    reportHotVod(window.varCurrentTime, latestParams)
    const params = {
      playProgress: parseInt(window.varCurrentTime),
      totalProgress: parseInt(window.varDuration || 0),
      from: 3,
      ...latestParams,
      lId: latestParams.lId
    }
    if (params.playProgress < 10) {
      return
    }
    if (token) {
      reportVodHistory(params, token)
    } else {
      cacheHistory('VOD', {
        cid: latestParams.cid,
        lId: latestParams.lId,
        num: latestParams.num,
        playProgress: params.playProgress
      })
    }
  } else {
    if (token) {
      reportLiveHistory(latestParams, token)
    } else {
      const newItem = {
        ...latestParams,
        playTime: parseInt(new Date().valueOf() / 1000)
      }
      cacheHistory('LIVE', newItem)
    }
  }
}

const Index = props => {
  const router = useRouter()
  const { from } = props
  const hlsConfig = constConfig.hlsConfig
  // src变化，切换源&上报历史记录-只有点播剧集的时候才需要使用
  useEffect(() => {
    return () => {
      reportHistory(from)
    }
  }, [router.query])
  // 页面刷新或关闭时，上报进度
  useEffect(() => {
    const handleBeforeUnload = () => {
      reportHistory(from)
    }
    window.addEventListener('beforeunload', handleBeforeUnload)
    return () => {
      window.removeEventListener('beforeunload', handleBeforeUnload)
    }
  }, [])

  return (
    <div style={constConfig.style}>
      <ReactVideo {...omit(props, ['style'])} style={constConfig.style} hlsConfig={hlsConfig} />
    </div>
  )
}

Index.useSetErrorCode = useSetErrorCode
export default Index
